import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class JDBCDemo2 {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        //1、创建数据源（DataSource）对象
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");

        //2、和数据库进行连接
        Connection connection = dataSource.getConnection();

        //3、构造sql语句
        String sql = "select * from student";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        //4、执行SQL语句
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            int id = resultSet.getInt("id");//按照列名获取数据
            String name = resultSet.getString("name");
            System.out.println(id+" " + name);
        }
        //5、关闭连接等资源
        preparedStatement.close();
        connection.close();
    }
}
